let redis = require('redis')

module.exports = {
  client: null,
  config: {
    ip: '127.0.0.1',
    port: 6379,
    pswd: 'test',
    cacheDBIndex: 8
  },
  init: function () {
    if (this.client !== null) return
    this.client = redis.createClient(this.config.port, this.config.ip, {auth_pass: this.config.pswd})
    this.client.on('ready', function (res) {
      console.log('redis ready')
    })
    this.client.on('error', function (err) {
      console.log('redis error: ' + err)
    })
  },
  setCache: function (key, value, expire) {
    let $this = this
    return new Promise((resolve, reject) => {
      $this.client.select(this.config.cacheDBIndex, function (error) {
        if (error) {
          return resolve({success: false, msg: 'redis select db error: ' + error})
        } else {
          $this.client.set(key, value, function (error, res) {
            if (error) {
              resolve({success: false, msg: 'redis set value error: ' + error})
            } else {
              $this.client.expire(key, expire)
              resolve({success: true})
            }
          })
        }
      })
    })
  },
  existCache: function (key) {
    let $this = this
    return new Promise((resolve, reject) => {
      $this.client.select(this.config.cacheDBIndex, function (error) {
        if (error) {
          resolve({success: false, msg: 'redis select db error: ' + error})
        } else {
          $this.client.exists(key, function (error, res) {
            if (error) {
              resolve({success: false, msg: 'redis get value error: ' + error})
            } else {
              resolve({success: true})
            }
          })
        }
      })
    })
  },
  getCache: function (key) {
    let $this = this
    return new Promise((resolve, reject) => {
      $this.client.select(this.config.cacheDBIndex, function (error) {
        if (error) {
          resolve({success: false, msg: 'redis select db error: ' + error})
        } else {
          $this.client.get(key, function (error, res) {
            if (error) {
              resolve({success: false, msg: 'redis get value error: ' + error})
            } else {
              resolve({success: true, data: JSON.parse(res)})
            }
          })
        }
      })
    })
  },
  removeCache: function (key) {
    let $this = this
    return new Promise((resolve, reject) => {
      $this.client.select(this.config.cacheDBIndex, function (error) {
        if (error) {
          resolve({success: false, msg: 'redis select db error: ' + error})
        } else {
          $this.client.del(key, function (error, res) {
            if (error) {
              resolve({success: false, msg: 'redis get value error: ' + error})
            } else {
              resolve({success: true})
            }
          })
        }
      })
    })
  }
}
